package club.hicode.daydayup.rpc.demo.client;

import club.hicode.daydayup.rpc.MicRegister;
import club.hicode.daydayup.rpc.base.MicService;
import club.hicode.daydayup.rpc.demo.client.frame.ClientStart;
import club.hicode.daydayup.rpc.demo.common.Caculator;
import club.hicode.daydayup.rpc.demo.common.Transcate;
import cn.hutool.json.JSONUtil;
import com.github.sd4324530.jtuple.Tuple2;
import io.netty.channel.Channel;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Rpc工厂
 * @author Liu Chunfu
 * @date 2018-08-31 上午11:32
 **/
public class RpcFactory {

	public static <T> T createProxy(Class<T> tClass) {
		Object proxyInstance = Proxy
				.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, new InvocationHandler() {
					@Override
					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
						Class<?> declaringClass = method.getDeclaringClass();
						MicService annotation = declaringClass.getAnnotation(MicService.class);
						String appName = annotation.value();

						Tuple2<String, Integer> target = MicRegister.target(appName);
						//String ip = target.first;
						//Integer port = target.second;
						Channel channel = ClientStart.CHANNEL;
						Transcate transcate = new Transcate(method.getName(), args);
						channel.writeAndFlush(JSONUtil.toJsonStr(transcate));
						
						return null;
					}
				});
		return (T) proxyInstance;
	}

}
